<?php
declare(strict_types=1);

namespace app\index\taglib;

use think\template\TagLib;

class Cms extends TagLib
{
    protected const _WEBSITE_CODE_SESSION_KEY = 'website';

    protected $tags = [
        'typename' => ['attr' => 'cid', 'close' => 1], // 单个栏目
        'channel'  => ['attr' => 'cid,type', 'close' => 1], // 遍历栏目
        'article'  => ['attr' => 'cid,flag,row', 'close' => 1], // 文档列表，支持文档标签
        'list'     => ['attr' => 'lang', 'close' => 1], // 文档列表，支持翻页
        'page'     => ['attr' => 'light', 'close' => 0], // 文档列表，分页连接
        'next'     => ['attr' => '', 'close' => 1], // 当前文档：上一页、下一页
        'ad'       => ['attr' => 'cid,row', 'close' => 1], // 广告列表
        'feedback' => ['attr' => '', 'close' => 1], // 留言板
    ];

    // 单个栏目
    public function tagtypename($tag, $content)
    {
        $cid            = isset($tag['cid']) ? intval($tag['cid']) : '$visitCid??0';
        $websiteCodeKey = self::_WEBSITE_CODE_SESSION_KEY;
        return <<<str
<?php
\$_websiteBusiness = new \app\common\business\Website();
\$_websites        = \$_websiteBusiness->getAllWebsite();
\$_website         =\$_websites[session('$websiteCodeKey')] ?? [];

\$_categoryBusiness = new \app\common\business\Category(session('$websiteCodeKey'));
\$field = \$_categoryBusiness->findCategoryById(\$_website['cdn_domain'], $cid);
if(\$field):
?>
    {$content}
<?php 
endif;
unset(\$field);
?>
str;
    }

    // 遍历栏目
    public function tagchannel($tag, $content)
    {
        $visitCid       = isset($tag['cid']) ? intval($tag['cid']) : '$visitCid??0';
        $type           = isset($tag['type']) ? trim($tag['type']) : 'top';
        $websiteCodeKey = self::_WEBSITE_CODE_SESSION_KEY;
        return <<<str
<?php
\$_websiteBusiness = new \app\common\business\Website();
\$_websites        = \$_websiteBusiness->getAllWebsite();
\$_website         =\$_websites[session('$websiteCodeKey')] ?? [];

\$_categoryBusiness = new \app\common\business\Category(session('$websiteCodeKey'));
\$_channels = \$_categoryBusiness->getChannels(\$_website['cdn_domain'], $visitCid, '$type');
if(\$_channels):
    foreach(\$_channels as \$_key=> \$field):
?>
        {$content}
<?php
    endforeach;
endif;
unset(\$field);
?>
str;
    }

    // 文档列表，支持文档标签
    public function tagarticle($tag, $content)
    {
        $row            = isset($tag['row']) ? intval($tag['row']) : 0;
        $flag           = isset($tag['flag']) ? trim($tag['flag']) : '';
        $cid            = isset($tag['cid']) ? intval($tag['cid']) : '$visitCid??0';
        $websiteCodeKey = self::_WEBSITE_CODE_SESSION_KEY;

        return <<<str
<?php
\$_aids            = input('post.aids',[]);
\$_websiteBusiness = new \app\common\business\Website();
\$_websites        = \$_websiteBusiness->getAllWebsite();
\$_website         =\$_websites[session('$websiteCodeKey')] ?? [];

// 文档标签
\$_flagBusiness = new \app\common\business\Flag(session('$websiteCodeKey'));
\$_flags = \$_flagBusiness->getAllFlag();
\$_flag =\$_flags['$flag']??[];
\$_flagId = \$_flag['id']??0;

// 栏目
\$_categoryBusiness = new \app\common\business\Category(session('$websiteCodeKey'));
\$_curCategory      = \$_categoryBusiness->findCategoryById(\$_website['cdn_domain'], $cid);
if(\$_curCategory): 
    // 模型
    \$_moduleBusiness   = new \app\common\business\Module(session('$websiteCodeKey'));
    \$_module           = \$_moduleBusiness->findModuleById(\$_curCategory['module_id']);
    
    // 文档
    \$_articleBusiness  = new \app\common\business\Article(session('$websiteCodeKey'),\$_module['code']);
    \$_childrenIds      = $cid ? array_merge([$cid], \$_categoryBusiness->getCurCategoryChildrenIds($cid)) : [];
    \$_where            = [['category_id','in',\$_childrenIds],'status'=>\app\common\model\CommonBase::IS_ENABLE_STATUS];
    if(!empty(\$_aids)) {
        \$_where[] = ['p.id','in',\$_aids];
    }
    \$_articleRes       = \$_articleBusiness->getArticleList(\$_website['cdn_domain'], 1,$row,\$_where,\$_flagId);
    if(\$_articleRes):
        foreach(\$_articleRes['rows'] as \$_key => \$field):
?>
            {$content}
    <?php 
        endforeach;
    endif;
endif;
unset(\$field);
?>
str;
    }

    // 文档列表，支持翻页
    public function taglist($tag, $content)
    {
        $cid            = '$visitCid??0';
        $page           = '$page??1';
        $lang           = isset($tag['lang']) ? trim($tag['lang']) : '';
        $noRecord       = $lang == 'cn' ? '没有找到符合条件的记录' : 'not found record';
        $websiteCodeKey = self::_WEBSITE_CODE_SESSION_KEY;

        return <<<str
<?php
\$_websiteBusiness = new \app\common\business\Website();
\$_websites        = \$_websiteBusiness->getAllWebsite();
\$_website         =\$_websites[session('$websiteCodeKey')] ?? [];

// 栏目
\$_categoryBusiness = new \app\common\business\Category(session('$websiteCodeKey'));
\$_curCategory      = \$_categoryBusiness->findCategoryById(\$_website['cdn_domain'], $cid);
\$_totalPage        = 0;
if(\$_curCategory):
    // 模型
    \$_moduleBusiness   = new \app\common\business\Module(session('$websiteCodeKey'));
    \$_module           = \$_moduleBusiness->findModuleById(\$_curCategory['module_id']);
    
    // 文档
    \$_attribute        = input('get.attribute', '','trim');
    \$_key              = input('get.keywords', '','trim');
    \$_childrenIds      = $cid ? array_merge([$cid], \$_categoryBusiness->getCurCategoryChildrenIds($cid)) : [];
    \$_where            = [['category_id','in',\$_childrenIds],['title','like','%'.\$_key.'%'],'status'=>\app\common\model\CommonBase::IS_ENABLE_STATUS];
    \$_articleBusiness  = new \app\common\business\Article(session('$websiteCodeKey'),\$_module['code']);
    \$_articleRes       = \$_articleBusiness->getArticleListWithPage(\$_website['cdn_domain'], \$_curCategory, \$_where, $page, \$_attribute);
    
    \$_totalPage   = \$_articleRes['totalPage'];
    \$_pageSize    = \$_articleRes['totalPage'];
    \$_count       = \$_articleRes['count'];
    \$_categoryUri = \$_articleRes['categoryUri'];
    if(\$_articleRes['count']):
        foreach(\$_articleRes['rows'] as \$_key => \$field):
?>
            {$content}
<?php 
        endforeach;
    else:
       echo '$noRecord';
    endif;
endif;
unset(\$field);
?>
str;
    }

    // 文档列表，支持翻页
    public function tagpage($tag)
    {
        $lightColor = isset($tag['light']) ? trim($tag['light']) : '#ff0000';
        $page       = '$page??1';
        return <<<str
<style>
.page {
    display: inline-block;
    list-style: none;
    margin-top: 20px;
}
.page li {
   display: inline-block;
}
.page li a,.page li span {
    display: block;
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    padding: 2px 5px;  
}
.page li a {
    border: 1px solid #ccc;    
}
.page .cur-item span {
    border: 1px solid #ccc;    
    background: $lightColor;
    color: #fff;
}
</style>
<ul class ="page">
<?php
if (\$_totalPage && \$_totalPage!=1):
    \$_curPage            = $page;
    \$_defaultShowPageNum = 5;
    \$_startPage          = max(1, \$_curPage - floor(\$_defaultShowPageNum / 2));
    \$_endPage            = min(\$_totalPage, \$_startPage + \$_defaultShowPageNum - 1);
    \$_startPage          = max(1, \$_endPage - \$_defaultShowPageNum + 1);
    \$_key                = input('get.keywords', '','trim');
    
    if(!\$_key):
?>
        <li><a href="{\$_categoryUri}/p/{\$_curPage<=1?1:\$_curPage-1}.html"> &lt;&lt; </a></li>
        <?php if (\$_startPage !=1):?>
            <li><span>...</span></li>    
        <?php endif;?>
        <?php for(\$_i = \$_startPage ;\$_i<=\$_endPage;\$_i++):?>
            <li class="<?php if(\$_curPage == \$_i):?>cur-item<?php endif;?>">
                <?php if(\$_curPage == \$_i):?>
                    <span>{\$_i}</span>
                <?php else:?>
                    <a href="{\$_categoryUri}/p/{\$_i}.html">{\$_i}</a>
                <?php endif;?>
            </li> 
        <?php endfor;?>
        <?php if (\$_endPage !=\$_totalPage):?>
            <li><span>...</span></li>    
        <?php endif;?>
        <li><a href="{\$_categoryUri}/p/{\$_curPage+1>\$_totalPage?\$_totalPage:\$_curPage+1}.html"> &gt;&gt; </a></li>
  
    <?php else: ?>
        <?php \$_uri = ltrim(\$_categoryUri,'/')?>
        <li><a href="/search?keywords={\$_key}&p={\$_curPage<=1?1:\$_curPage-1}&uri={\$_uri}"> &lt;&lt; </a></li>
        <?php if (\$_startPage !=1):?>
            <li><span>...</span></li>    
        <?php endif;?>
        <?php for(\$_i = \$_startPage ;\$_i<=\$_endPage;\$_i++):?>
            <li class="<?php if(\$_curPage == \$_i):?>cur-item<?php endif;?>">
                <?php if(\$_curPage == \$_i):?>
                    <span>{\$_i}</span>
                <?php else:?>
                    <a href="/search?keywords={\$_key}&p={\$_i}&uri={\$_uri}">{\$_i}</a>
                <?php endif;?>
            </li> 
        <?php endfor;?>
        <?php if (\$_endPage !=\$_totalPage):?>
            <li><span>...</span></li>    
        <?php endif;?>
        <li><a href="/search?keywords={\$_key}&p={\$_curPage+1>\$_totalPage?\$_totalPage:\$_curPage+1}&uri={\$_uri}"> &gt;&gt; </a></li>
    <?php endif;?>
<?php endif;?>
 </ul>
str;

    }

    // 当前文档：上一页、下一页
    public function tagnext($tag, $content)
    {
        $cid            = '$visitCid??0';
        $aid            = '$visitAid??0';
        $websiteCodeKey = self::_WEBSITE_CODE_SESSION_KEY;
        return <<<str
<?php
\$_websiteBusiness = new \app\common\business\Website();
\$_websites        = \$_websiteBusiness->getAllWebsite();
\$_website         =\$_websites[session('$websiteCodeKey')] ?? [];

// 栏目
\$_categoryBusiness = new \app\common\business\Category(session('$websiteCodeKey'));
\$_curCategory      = \$_categoryBusiness->findCategoryById(\$_website['cdn_domain'], $cid);
if(\$_curCategory):
    // 模型
    \$_moduleBusiness   = new \app\common\business\Module(session('$websiteCodeKey'));
    \$_module           = \$_moduleBusiness->findModuleById(\$_curCategory['module_id']);
    
    // 文档
    \$_childrenIds      = $cid ? array_merge([$cid], \$_categoryBusiness->getCurCategoryChildrenIds($cid)) : [];
    \$_where            = [['category_id','in',\$_childrenIds],'status'=>\app\common\model\CommonBase::IS_ENABLE_STATUS];
    \$_articleBusiness  = new \app\common\business\Article(session('$websiteCodeKey'),\$_module['code']);
    \$field             = \$_articleBusiness->getPrevAndNextArticle($aid);
?>
    {$content}
<?php 
endif;
unset(\$field); ?>
str;
    }

    // 广告列表
    public function tagad($tag, $content)
    {
        $cid            = isset($tag['cid']) ? intval($tag['cid']) : 0;
        $row            = isset($tag['row']) ? intval($tag['row']) : 0;
        $websiteCodeKey = self::_WEBSITE_CODE_SESSION_KEY;
        return <<<str
<?php
\$_websiteBusiness = new \app\common\business\Website();
\$_websites        = \$_websiteBusiness->getAllWebsite();
\$_website         =\$_websites[session('$websiteCodeKey')] ?? [];

\$_adBusiness = new \app\common\business\Ad(session('$websiteCodeKey'));
\$_ads = \$_adBusiness->getAllAd(\$_website['cdn_domain'],['position_id'=>$cid,'status'=>\app\common\model\CommonBase::IS_ENABLE_STATUS],$row);
if(\$_ads):
    foreach(\$_ads as \$_key => \$field): 
?>
        {$content}
<?php
    endforeach;
endif;
unset(\$field);
?>
str;
    }

    // 自定义表单，留言板
    public function tagfeedback($tag, $content)
    {
        $cid            = isset($tag['cid']) ? intval($tag['cid']) : 0;
        $websiteCodeKey = self::_WEBSITE_CODE_SESSION_KEY;
        return <<<str
<?php
\$_feedbackFieldBusiness = new \app\common\business\FeedbackField(session('$websiteCodeKey'));
\$_fields = \$_feedbackFieldBusiness->getAllFeedbackField(['form_id'=>$cid,'status'=>\app\common\model\CommonBase::IS_ENABLE_STATUS]);
if(\$_fields):
    foreach(\$_fields as \$_key => \$field): 
?>
        {$content}
<?php
    endforeach;
endif;
unset(\$field);
?>
str;
    }
}
